package com.hmall.order.mq;

import com.hmall.common.client.ItemClient;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.service.IOrderDetailService;
import com.hmall.order.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;

/**
 * MQ消息监听器
 */
@Component
@Slf4j
public class OrderListener {

    @Autowired
    private ItemClient itemClient;

    @Autowired
    private IOrderService orderService;

    @Autowired
    private IOrderDetailService orderDetailService;

    /**
     * 定义延迟队列，监听订单的支付状态
     * @param orderId
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("hmMall.order.pay-queue"),//队列名称
            exchange = @Exchange(
                    name = "hmMall-order.pay-exchange",  //交换机名称
                    delayed = "true"),   //延迟队列
            key = {"order.pay"}//主题名称
    ))
    public void listenOrderPayStatus(String orderId) throws IOException {
        log.info("30分钟已到，开始检查订单状态：{}" , orderId);
        //1 根据id查询订单信息
        Order order = orderService.getById(orderId);
        //2 判断订单状态，如果是不是1（1:未付款 2:已付款-未发货 3:已发货-未确认 4:确认收货-易成功 5:交易取消-订单关闭 6:交易结束），直接丢弃消息不处理，保证消息幂等性。
        if(order.getStatus()!=1){
            return;
        }
        //3 修改订单状态为5
        order.setStatus(5);
        order.setCloseTime(new Date());
        order.setUpdateTime(new Date());
        orderService.updateById(order);
        //4 根据订单id查询订单详情
        OrderDetail orderDetail = orderDetailService.query().eq("order_id", order.getId()).one();
        //5 远程调用，恢复扣减的库存
        itemClient.updateStock(orderDetail.getItemId(),orderDetail.getNum());
    }
}
